<template>
  <div class="interface">
    <el-radio-group v-model="activeName" class="tab">
      <el-radio-button :label="item.label" v-for="(item, index) in tableArr" :key="index">{{item.name}}</el-radio-button>
    </el-radio-group>
    <el-button type="text"
               size="mini"
               class="interface-old primary_btn"
               icon="iconfont icon-zongshichang fl"
               v-if="flowStepOld.length"
               @click.stop="getOldUrl">
      &nbsp;{{$t('configLazyLoad.businessConfig.oldVersionDockingPreview')}}
    </el-button>
    <div class="outflowBox" v-show="activeName === 'outflow'">
      <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip')}}</p>
      <p class="noticeTittle">
        {{$t('configLazyLoad.businessConfig.tip6')}}<template v-if="!$store.state.oemObj.oemFlag">7moor</template>{{$t('configLazyLoad.businessConfig.tip7')}}<br />
        {{$t('configLazyLoad.businessConfig.tip8')}}</p>
      <p class="interface-layout">
        <el-button type="text" size="mini" @click.stop="getWorkOrderFun" v-if="!$store.state.oemObj.oemFlag">{{$t('configLazyLoad.businessConfig.lookInterconnectionDocuments')}}</el-button>
        <el-button type="text" size="mini" @click.stop="getExample">{{$t('configLazyLoad.businessConfig.lookBusinessOutboundConnection')}}</el-button>
      </p>
      <div class="addOutFlow">
        <el-button type="text" size="mini" icon="el-icon-plus" @click.stop="addNewUrl">{{$t('configLazyLoad.businessConfig.addOutgoingURL')}}</el-button>
        <ul>
          <li class="outFLowCard" v-for="(item, index) in outFlowList" :key="index">
            <div class="outFLowCard-head">
              <span>{{$t('configLazyLoad.businessConfig.outgoingURL')}}{{index + 1}}</span>
              <span class="del" @click="delFun(index)">{{$t('public.delete')}}</span></div>
            <div class="outFlowCard-content">
              <p>url:</p>
              <el-input v-model="item.url" :placeholder="$t('configLazyLoad.businessConfig.pleaseEnterURL')" size="mini"></el-input>
              <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip9')}}</p>
              <p>{{$t('configLazyLoad.businessConfig.dockingProcess&Fields')}}
                <el-checkbox v-model="item.checkAll" @change="handleCheckAllChange($event, index)">{{$t('public.checkAll')}}</el-checkbox>
              </p>
              <div class="checkBoxChild">
                <el-checkbox-group v-model="item.checkedCode" @change="handleCheckedChange($event, index)" size="small">
                  <el-checkbox v-for="(checkedItem, checkedIndex) in flowStepInterface" :label="checkedItem._id" :key="checkedIndex" border class="checkbox">{{checkedItem.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
              <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip10')}}</p>
            </div>
          </li>
        </ul>
        <p class="btn-wrap"><el-button type="primary" class="primary_btn" @click="saveFun">{{$t('public.save')}}</el-button></p>
      </div>
    </div>
    <div class="inflowBox" v-show="activeName === 'inflow'">
      <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip')}}</p>
      <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip11')}}</p>
      <p class="noticeTittle">{{$t('configLazyLoad.businessConfig.tip12')}}</p>
      <p class="noticeTittle">
        <el-button type="text" size="mini" @click.stop="getWorkOrderFun" v-if="!$store.state.oemObj.oemFlag">{{$t('configLazyLoad.businessConfig.lookInterconnectionDocuments')}}</el-button>
        <el-button type="text" size="mini" @click.stop="getExample">{{$t('configLazyLoad.businessConfig.lookBusinessComeboundConnection')}}</el-button>
      </p>
      <p class="inflow-url">URL:
        <span id="copyUrl">{{inUrl}}</span>
      </p>
      <p style="text-indent: 28px">
        <el-button type="text" size="mini" @click.stop="copyUrlFun">{{$t('configLazyLoad.businessConfig.clickCopyURLAddress')}}</el-button>
      </p>
    </div>
    <el-dialog :close-on-click-modal="false" :append-to-body="true" :modal-append-to-body="true" lock-scroll top="10vh" :visible="dialogObj.isShow" :title="dialogObj.title" size="middle" @close="dialogObj.isShow = false">
      <el-row class="interface-example" :gutter="20" v-show="dialogObj.type === 'example'">
        <el-col :span="12">
          <span class="example-label">{{$t('configLazyLoad.businessConfig.repairOrderSteps')}}</span>
          <el-select size="mini" v-model.trim="exampleForm.stepId" filterable placeholder="" @change="stepChange" class="example-select" :placeholder="$t('public.pleasePick')">
            <el-option  v-for="item in flowSteps"
                        :label="item.name"
                        :key="item._id"
                        :value="item._id">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          <span class="example-label">{{$t('configLazyLoad.businessConfig.stepAction')}}</span>
          <el-select size="mini" v-model.trim="exampleForm.actionId" filterable placeholder="" @change="actionChange" class="example-select" :placeholder="$t('public.pleasePick')">
            <el-option  v-for="item in currentStep.actions || []"
                        :label="item.name"
                        :key="item._id"
                        :value="item._id">
            </el-option>
          </el-select>
        </el-col>
        <div class="code" v-if="activeName === 'outflow'">
          {
          _id: 'xxxxxxx',//工单id<br>
          fields:[<br>
          <template v-for="(one, index) in exampleForm.fields">
            {name: '{{one.name}}',type: '{{one.type}}',value: {{one.value}}}
            {{index+1 !== exampleForm.fields.length? ',': ''}}
            <br>
          </template>
          ],<br>
          user: '工号',//处理人<br>
          createTime: 'yyyy-mm-dd HH:mm:ss',<br>
          flowInfo: '步骤信息',<br>
          action: '{{exampleForm.actionName}}',//动作名称<br>
          createTimestamp: 1505716040000//创建时间毫秒数<br>
          priority: '1' // 工单优先级，创建工单时可传'1'，'2','3'表示普通，紧急，很紧急<br>
          }
        </div>
        <div class="code" v-else>
          {
          _id: '工单id',// 工单id、工单编号如果均为空则表示新建工单<br>
          number: '工单编号',// 工单id、工单编号如果均为空则表示新建工单<br>
          customerId: '客户id',// 如果为空则表示未知客户<br>
          fields:[<br>
          <template v-for="(one, index) in exampleForm.fields">
            {name: '{{one.name}}',type: '{{one.type}}',value: {{one.value}}}
            {{index+1 !== exampleForm.fields.length? ',': ''}}{{one.required === 'required'? '//必传': ''}}
            <br>
          </template>
          ],<br>
          targetUser: '工号|auto',// 指派给谁处<br>
          createUser: '工号',<br>
          flowName: '工单流名称',// 必传<br>
          comment: '备注',<br>
          stepName: '工单步骤名称',// 必传<br>
          action: '{{exampleForm.actionName}}', // 动作名称<br>
          priority: '1' // 工单优先级，创建工单时可传'1'，'2','3'表示普通，紧急，很紧急<br>
          }
        </div>
      </el-row>
      <el-row v-show="dialogObj.type === 'oldUrl'" class="interface-example" >
        <div class="noticeTittle" style="padding-bottom: 15px;">
          {{$t('configLazyLoad.businessConfig.tip13')}}<br>
          {{$t('configLazyLoad.businessConfig.tip14')}}
        </div>
        <el-col :span="18" v-if="flowStepOld.length">
          <span class="example-label">{{$t('configLazyLoad.businessConfig.outboundInterconnectionProcedure')}}</span>
          <el-select size="mini"
                     filterable
                     @change="stepOldChange"
                     value-key="_id"
                     v-model="oldUrlForm.stepId"
                     style="width: calc(100% - 90px); margin-bottom: 15px"
                     :placeholder="$t('public.pleasePick')">
            <el-option  v-for="item in flowStepOld"
                        :label="item.name"
                        :key="item._id"
                        :value="item">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="18" v-if="flowStepOld.length">
          <span class="example-label">{{$t('configLazyLoad.businessConfig.outgoingStepURL')}}</span>
          <el-input class="example-select" disabled v-model="oldUrlForm.stepOldUrl"></el-input>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
  import Clipboard from 'clipboard-js'
  import {checkform} from '@/utils/validate'
  import {deepClone} from '@/utils/m7Utils'
  export default {
    name: 'interface',
    data () {
      return {
        activeName: 'outflow',
        tableArr: [
          {label: 'outflow', name: this.$t('configLazyLoad.businessConfig.outboundBusinessInterconnection')},
          {label: 'inflow', name: this.$t('configLazyLoad.businessConfig.flowIntoBusinessDocking')}
        ],
        outFlowList: [
        ],
        exampleForm: {
          stepId: '',
          actionId: '',
          actionName: '',
          fields: []
        },
        currentStep: {},
        inUrl: '',
        dialogObj: {
          isShow: false,
          title: this.$t('configLazyLoad.businessConfig.outboundBusinessEm'),
          type: 'example'
        },
        oldUrlForm: {
          stepOldUrl: '',
          stepId: ''
        }
      }
    },
    inject: ['busType'],
    computed: {
      // 流出步骤
      flowSteps () {
        let steps = this.$store.state.config.businessConfig.detailFlow.flowSteps || []
        return steps.filter((item) => item.type !== 'sys')
      },
      // 老板配置了流出url的步骤
      flowStepOld () {
        let flowSteps = this.flowSteps || []
        let data = flowSteps.filter((item) => {
          if (item.outflowInterface && item.outflowInterface.url) {
            return true
          }
        })
        if (this.bacInfoUrl) {
          data.push({_id: 'bacInfoUrl', name: this.$t('configLazyLoad.businessConfig.repairNote'), outflowInterface: {url: this.bacInfoUrl}})
        }
        return data
      },
      // 老版工单备注流出url
      bacInfoUrl () {
        let flowInfo = this.$store.state.config.businessConfig.detailFlow.flowInfo
        return flowInfo.interfaceUrl
      },
      // 工单备注 + 流出步骤
      flowStepInterface () {
        let arr = [{_id: 'isComment', name: this.$t('configLazyLoad.businessConfig.noteField')}]
        let flowSteps = this.flowSteps
        return arr.concat(flowSteps.map(({_id, name}) => {
          return {_id, name}
        }))
      },
      // 工单字段
      flowFieldsArr () {
        return this.$store.state.config.businessConfig[this.busType].allFields || []
      }
    },
    methods: {
      // 初始化该组件
      initData () {
        let data = this.$store.state.config.businessConfig.detailFlow.flowInfo.dockingUrl || []
        this.outFlowList = []
        if (data.length === 0) {
          let addOutFlowList = {
            url: '',
            checkAll: false,
            checkedCode: []
          }
          this.outFlowList.push(addOutFlowList)
        } else {
          data.forEach((item) => {
            let obj = {
              url: item.url,
              checkAll: false,
              checkedCode: deepClone(item.steps || [])
            }
            if (item.isComment) {
              obj.checkedCode.push('isComment')
            }
            if (this.flowStepInterface.length === obj.checkedCode.length) {
              obj.checkAll = true
            }
            this.outFlowList.push(obj)
          })
        }
      },
      // 对接实例，动作改变
      actionChange (value) {
        this.exampleForm.actionId = value
        let field = []
        if (this.currentStep.isBegin) {
          field = this.generateBusinessFieldsExample(this.currentStep.stepFields || [])
        }
        let action = this.currentStep.actions || []
        this.exampleForm.actionName = ''
        for (let i = 0; i < action.length; i++) {
          if (action[i]._id === value) {
            field = field.concat(this.generateBusinessFieldsExample(action[i].actionFields || []))
            this.exampleForm.actionName = action[i].name
            break
          }
        }
        this.exampleForm.fields = field
      },
      // 对接实例，步骤改变
      stepChange (value) {
        let steps = this.flowSteps
        this.currentStep = {}
        this.exampleForm.stepId = value
        this.exampleForm.actionId = ''
        steps.some((item) => {
          if (item._id === value) {
            this.currentStep = item
            return true
          }
        })
        this.actionChange('')
      },
      // 旧版，工单步骤改变
      stepOldChange (item) {
        this.oldUrlForm.stepId = item
        this.oldUrlForm.stepOldUrl = item.outflowInterface.url
      },
      // 生成工单字段示例
      generateBusinessFieldsExample (fieldsData, flag) {
        let arr = []
        for (let i = 0; i < fieldsData.length; i++) {
          let item = fieldsData[i].cols
          for (let m = 0; m < item.length; m++) {
            let itemTwo = item[m].fields
            for (let n = 0; n < itemTwo.length; n++) {
              let itemThree = itemTwo[n]
              let field = this.flowFieldsArr.filter((item) => item._id === itemThree._id)[0]
              if (field) {
                let type = field.type
                let result = {name: field.name, type: field.type, required: field.required}
                switch (type) {
                  case 'single':
                    result.value = '\'abc\''
                    break
                  case 'multi':
                    result.value = '\'abc\''
                    break
                  case 'date':
                    result.value = '\'YYYY-MM-DD\''
                    break
                  case 'time':
                    result.value = '\'HH:MM:SS\''
                    break
                  case 'datetime':
                    result.value = '\'YYYY-MM-DD HH:MM:SS\''
                    break
                  case 'number':
                    result.value = 1
                    break
                  case 'dropdown':
                    result.value = '[\'select1\']'
                    break
                  case 'dropdownTree':
                    result.value = '[\'select1\']'
                    break
                  case 'checkbox':
                    result.value = '[\'checkbox1\',\'checkbox2\',\'checkbox3\']'
                    break
                  case 'radio':
                    result.value = '\'abc\''
                    break
                  case 'file':
                    result.value = '[{name:\'123.jpg\',value:\'base64\u7801\'}]'
                    break
                  default :
                    console.log('the type [' + type + '] is not support!')
                }
                arr.push(result)
              }
            }
          }
        }
        return arr
      },
      // 打开示例
      getExample () {
        this.dialogObj.isShow = true
        this.dialogObj.type = 'example'
        this.dialogObj.title = this.activeName === 'outflow' ? this.$t('configLazyLoad.businessConfig.outboundBusinessEm') :  this.$t('configLazyLoad.businessConfig.flowIntoBusinessEm')
        if (this.flowSteps.length) {
          this.stepChange(this.flowSteps[0]._id)
        }
      },
      // 打开老版步骤url展示
      getOldUrl () {
        this.dialogObj.isShow = true
        this.dialogObj.type = 'oldUrl'
        this.dialogObj.title = this.$t('configLazyLoad.businessConfig.oldVersionDockingPreview')
        if (this.flowStepOld.length) {
          this.stepOldChange(this.flowStepOld[0])
        }
      },
      // 跳转到开发者中心
      getWorkOrderFun () {
        let url = 'https://developer.7moor.com/v2docs/workOrder/'
        window.open(url, '_blank')
      },
      copyUrlFun () {
        Clipboard.copy(this.inUrl).then(() => {
          this.$message.success(this.$t('configLazyLoad.businessConfig.URLReplicated'))
        })
      },
      // 流出步骤多选框change
      handleCheckAllChange (val, index) {
        this.outFlowList[index].checkedCode = val ? this.flowStepInterface.map((item) => item._id) : []
      },
      addNewUrl () {
        if (this.outFlowList.length >= 10) {
          this.$message.error(this.$t('configLazyLoad.businessConfig.tip15'))
          return
        }
        let addOutFlowList = {
          url: '',
          checkAll: false,
          checkedCode: []
        }
        this.outFlowList.push(addOutFlowList)
      },
      handleCheckedChange (value, index) {
        let checkedCount = value.length
        this.outFlowList[index].checkAll = checkedCount === this.flowStepInterface.length
      },
      delFun (index) {
        this.outFlowList.splice(index, 1)
      },
      // 保存流出url
      saveFun () {
        // 表单校验
        let failure = this.outFlowList.some(({url, checkedCode}, index) => {
          if (!url) {
            this.$message.error(this.$t('configLazyLoad.businessConfig.outOfURL') + (index + 1) + this.$t('configLazyLoad.businessConfig.tip16'))
            return true
          } else if (checkform(url, 'Url')) {
            this.$message.error(this.$t('configLazyLoad.businessConfig.outOfURL') + (index + 1) + this.$t('configLazyLoad.businessConfig.tip17'))
            return true
          }
        })
        if (!failure) {
          let dockingUrl = this.outFlowList.map(({url, checkedCode}) => {
            let isComment = false
            let steps = []
            if (checkedCode.indexOf('isComment') !== -1) {
              isComment = true
            }
            steps = checkedCode.filter((item) => item !== 'isComment')
            return {url, steps, isComment}
          })
          let flow = this.$store.state.config.businessConfig.detailFlow.flowInfo
          this.$store.dispatch('saveBusinessDockingConfiguration', {_id: flow._id, dockingUrl}).then((res) => {
            if (res.success) {
              this.$store.commit('flowConfig/UPDATE_FLOW_INFO', {type: 'update', data: {dockingUrl}})
              this.$message.success(this.$t('monitor.saveSuccess'))
            }
          })
        }
      }
    },
    beforeMount () {
      // 获取流入url
      this.$store.dispatch('getCache', {type: 'restApiUrl'}).then((res) => {
        if (res && res.length) {
          let account = this.$store.state.session.account.account
          this.inUrl = res[0].code_value.handleBusiness + '/' + account + '?sig=xxxx'
        }
      })
    }
  }
</script>

<style scoped lang='stylus'>
  .interface
    padding-bottom 20px
    .tab
      margin 20px
    .outflowBox
      margin-left 20px
    .inflowBox
      margin-left 20px
    .interface-layout
      margin 5px 0px 10px
      span
        cursor pointer
    .addOutFlow
      .addIcon
        color #459AE9
        cursor pointer
      .outFLowCard
        border 1px solid #E7E7EB
        width 916px
        margin 10px 0px
      .outFLowCard-head
        padding 10px 20px
        border-bottom 1px solid #E7E7EB
        .del
          float right
          color #FF6B6B
          cursor pointer
      .outFlowCard-content
        padding 20px
        .checkBoxChild
          .checkbox
            margin 0 10px 10px 0
      .outFlowCard-content>p
        padding 5px
  .inflow-url
    padding-top 18px
  .btn-wrap
    padding-top 10px
    text-align center
  .interface-example
    padding 20px 0
    .example-label
      display inline-block
      padding-right 10px
    .example-select
      padding-bottom 15px
      width calc(100% - 80px)
  .code
    background-color #eee
    padding 15px
    max-height 60vh
    overflow-y: auto
    line-height 18px
    margin-bottom 10px
  .interface-old
    float right
    margin 20px 20px 0 0
    padding 0
  .noticeTittle
    color #3B5998
</style>
